<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :md="10">
        <el-card class="box-card">
          <div class="el-card__header">
            <el-icon><Share /></el-icon> 组织架构树

            <span class="rightmenu">
              <el-button
                class="btnaddroot"
                link
                @click="addRootOrg"
                v-hasPerm="'AbpIdentity.Roles'"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                添加根组织
              </el-button>
              <span style="font-size: 15px; padding: 2px 10px; color: #eee">|</span>
              <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                <el-button :icon="Refresh" link @click="getOrgTree()" />
              </el-tooltip>
            </span>
          </div>
          <el-scrollbar ref="scrollbar" class="orgcardscroller">
            <el-tree
              ref="orgTreeRef"
              :data="orgTree"
              :props="treeProps"
              default-expand-all
              highlight-current
              node-key="id"
              @node-contextmenu="contextmenuhandler"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node" slot-scope="{ node }">
                  <el-icon class="treeNodeIcon">
                    <FolderOpened v-if="node.expanded" />
                    <Folder v-else="node.expanded" />
                  </el-icon>
                  <span class="node-icon-label">{{ node.label }}</span>
                  <span style="font-size: 12px; margin-left: 3px; color: #a0a0a0"
                    >{{ data.userInOrgCount }} 组织成员
                  </span>
                </span>
              </template>
            </el-tree>
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :md="14">
        <el-card>
          <div slot="header" class="el-card__header">
            <span>当前组织：{{ currentClickOrg.displayName }}</span>
          </div>
          <div class="orgcardscroller">
            <template v-if="Object.keys(currentClickOrg).length == 0 ? false : true">
              <div class="cardbody">
                <el-button
                  v-hasPerm="'AbpIdentity.OrganitaionUnits.AddUseToOrganization'"
                  @click="addUserInOrg"
                  :icon="Plus"
                  type="primary"
                  >添加成员</el-button
                >
                <el-table style="width: 100%" :data="orgUserList">
                  <el-table-column
                    type="index"
                    width="100"
                    label="#"
                    align="center"
                  ></el-table-column>
                  <template v-for="item in columns">
                    <el-table-column
                      :prop="item.prop"
                      :label="item.label"
                      :min-width="item.width"
                      align="center"
                    >
                      <template v-slot="{ row }" v-if="item.prop == 'creationTime'">
                        {{ moment(row.creationTime).format(item.format) }}
                      </template>
                    </el-table-column>
                  </template>
                  <el-table-column label="操作" align="center">
                    <template #default="scope">
                      <el-button text type="primary" @click="deleteOrgUser(scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <div class="paging">
                  <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="tablePage.totalResult"
                    :page-size="tablePage.pageSize"
                    @change="handlePageChange"
                    v-model:current-page="tablePage.currentPage"
                  />
                </div>
              </div>
            </template>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div :style="classname" class="menu" v-if="showMenu">
      <ul>
        <li v-hasPerm="'AbpIdentity.OrganitaionUnits.Update'" @click="updateOrg">
          <i class="el-icon-edit"></i> 修改
        </li>
        <li v-hasPerm="'AbpIdentity.OrganitaionUnits.CreateSubOrg'" @click="addChildOrg">
          <i class="el-icon-document-add"></i> 添加子组织
        </li>
        <li v-hasPerm="'AbpIdentity.OrganitaionUnits.Delete'" @click="deleteOrg">
          <i class="el-icon-delete"></i> 删除
        </li>
      </ul>
    </div>
    <AddOrganization
      v-if="addVisable"
      :current-Node="currentCheckNode"
      @closedialogevent="(eventData:boolean)=>{addVisable= eventData}"
      @refresh="getOrgTree()"
    ></AddOrganization>

    <EditOrganization
      :current-Node="currentCheckNode"
      v-if="editVisable"
      @closedialogevent="(eventData:boolean)=>{editVisable= eventData}"
      @refresh="getOrgTree()"
    />
    <BindingUser
      v-if="bindVisable"
      :current-Org="currentClickOrg"
      @closedialogevent="(eventData:boolean)=>{bindVisable=eventData}"
      @refresh="getUserList()"
    />
  </div>
</template>
<script setup lang="ts">
import {
  Search,
  Plus,
  Share,
  Refresh,
  FolderOpened,
  Folder,
} from "@element-plus/icons-vue";
import {
  getOrganizationunitForTree,
  deleteOrganization,
} from "@/api/identity/organizationUnits/index";
import {
  getUsersInoOrganizationunit,
  removeUserFromOrg,
} from "@/api/identity/user/index";
import AddOrganization from "./components/AddOrganization.vue";
import EditOrganization from "./components/EditOrganization.vue";
import BindingUser from "./components/BindingUser.vue";
import moment from "moment";
const orgTree = ref<any>([]);
const addVisable = ref<boolean>(false);
const editVisable = ref<boolean>(false);
const bindVisable = ref<boolean>(false);
const treeProps = {
  children: "child",
  label: "displayName",
};

const currentClickOrg = ref<any>({});
const currentCheckNode = ref<any>({});
const classname = ref<any>({});
const showMenu = ref<boolean>(false);
const currentId = ref<String>("");
const currentName = ref<String>("");

const columns = ref([
  {
    label: "用户名",
    prop: "userName",
    width: 130,
  },

  {
    label: "创建时间",
    prop: "creationTime",
    width: 90,
    format: "YYYY-MM-DD HH:mm:ss",
  },
]);

const orgUserList = ref<any[]>();

const tablePage = ref<any>({
  currentPage: 1,
  pageSize: 10,
  totalResult: 0,
});

const getOrgTree = async () => {
  let param: any = {};
  orgTree.value = await getOrganizationunitForTree(param);
};
const addRootOrg = async () => {
  currentCheckNode.value = {};
  addVisable.value = true;
};

const handleNodeClick = async (data: any, node: any, tree: any, event: any) => {
  currentClickOrg.value = {};
  currentClickOrg.value = data;
  await getUserList();
  //console.log("handlNodeClick", currentClickOrg.value,orgUserList.value);
};

const getUserList = async () => {
  currentClickOrg.value;
  let param: any = {
    orgId: currentClickOrg.value.id,
    includeChildren: false,
    Sorting: "",
    SkipCount: (tablePage.value.currentPage - 1) * tablePage.value.pageSize,
    MaxResultCount: tablePage.value.pageSize,
  };

  let userInOrg = await getUsersInoOrganizationunit(param);
  orgUserList.value = userInOrg.items;
  tablePage.value.totalResult = userInOrg.totalCount;
};
const contextmenuhandler = (event: any, data: any, node: any, tree: any) => {
  //console.log("contextmenuhandler", event, data, node, tree);
  currentCheckNode.value = {};
  currentCheckNode.value = node;
  currentName.value = "";
  currentId.value = "";
  currentId.value = currentCheckNode.value?.data.id;
  currentName.value = currentCheckNode.value?.data.displayName;
  showMenu.value = true;
  classname.value = {
    position: "fixed",
    "z-index": "2000",
    left: event.clientX + 5 + "px",
    top: event.clientY + 7 + "px",
  };
  //console.log('contextmenuhandler',currentCheckNode.value)
};

const left = () => {
  showMenu.value = false;
  classname.value = {};
};

const updateOrg = () => {
  //console.log("editOrg");
  editVisable.value = true;
};

const addChildOrg = async () => {
  addVisable.value = true;
};

const deleteOrg = () => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteOrganization(currentId.value).then((res) => {
        if (res) {
          ElNotification({
            title: "提示",
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
          getOrgTree();
        }
      });
    })
    .catch();
};
function handlePageChange(currentPage: number, pageSize: number) {
  tablePage.value.currentPage = currentPage;
  getUserList();
  // searchfilter.maxResultCount = pageSize;
  // searchfilter.skipCount = (currentPage - 1) * pageSize;
}

const addUserInOrg = () => {
  bindVisable.value = true;
};

const deleteOrgUser = (row: any) => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //console.log("deleteuser", currentClickOrg.value);
      let param = {
        userId: row.id,
        orgId: currentClickOrg.value.id,
      };
      removeUserFromOrg(param).then((res) => {
        if (res) {
          ElNotification({
            title: "提示",
            message: "移除成功",
            type: "success",
            duration: 2000,
          });
          getUserList();
        }
      });
    })
    .catch(() => {
      console.log("取消");
    });
};
onMounted(async () => {
  await getOrgTree();
  document.body.addEventListener("click", () => {
    left();
  });
  document.body.addEventListener("scroll", () => {
    left();
  });
});
</script>
<style scoped type="sass">
.refresh-icon {
  padding: 3px 0;
  text-align: center;
  font-size: 12px;
  color: #66b1ff;
  cursor: pointer;
}
.btnaddroot {
  padding: 3px 0;
  font-size: 14px;
  font-family: "微软雅黑";
  line-height: 1;
}
.rightmenu {
  float: right;
  display: flex;
  justify-content: flex-start;
  align-content: center;
  line-height: 1;
  font-size: 12px;
}

:deep(.el-card__header) {
  padding: 0px 10px 5px 10px;

  font-size: 14px;
  font-family: "微软雅黑";
  border-bottom: 1px solid #ebeef5;
}
.refresh {
  font-size: 14px;
  vertical-align: middle;
  margin-top: 5px;
}

.box-card {
  font-size: var(--el-font-size-base);
}
.treeNodeIcon {
  font-size: 18px;

  margin-right: 5px;
}
.custom-tree-node {
  height: 26px;
  line-height: 26px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
  padding-right: 10px;
}
.orgcardscroller {
  height: calc(100vh - 180px);
  width: 98%;
}
.menu {
  color: black;
  background-color: #fff;
  box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08),
    0 9px 28px 8px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  /* padding: 0 14px; */
  text-align: left;
  margin: 0 auto;
  font-family: "微软雅黑";
  font-size: 12px;
}
ul {
  list-style-type: none;
  padding: 0px;
  margin: 6px 0;
}
li {
  height: 28px;
  padding: 0 14px;
  line-height: 28px;
}
ul li:hover {
  background-color: #eee;
  cursor: pointer;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #1890ff;
}
::v-deep .el-tree-node__label {
  font-size: 12px;
}

.header-toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.cardbody {
  padding-top: 10px;
}
</style>
